#include "QClientInterface.h"
#include "QClientInit.h"
#include "Discover.h"
#include "../QCommon/QCommon.h"
#include "../QCommon/events.h"
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/msg.h>

#include <iostream>
using namespace std;

#define TEST "/tmp/LaNq_TeSt"
QClientInit *init;
Discover *discover;
Notify *notify;

void start_QServer()
{
    pid_t pid;
    char cmd[100];
    strcpy(cmd,"ps -ef | grep -w 'LanQServer' | grep -v grep > ");
    strcat(cmd,TEST);
    system(cmd);
    int fd=open(TEST,O_RDWR);
    char ch;
    int size=read(fd,&ch,sizeof(ch));
    close(fd);
    unlink(TEST);
    if(size>0)
        return;
    if((pid=fork())==0)
    {
        if((pid=vfork())==0)
        {
            execl("./LanQServer","LanQServer",(char *)0);
        }
        exit(0);
    }
    wait(NULL);
    cout<<"Starting..."<<endl;
    sleep(2);
}

void start()
{
    start_QServer();
    init=new QClientInit();
    discover=new Discover();
    notify=new Notify();
}

vector<User> getOnlineUsers()
{
    return discover->getOnlineUsers();
}

void sendFile(string path,User &user)
{
    int fd=retrieve_msqid();
    FileAskEvent e;
    strcpy(e.dest_ip,user.ip.c_str());
    strcpy(e.src_ip,notify->getUser().ip.c_str());
    strcpy(e.file_name,path.c_str());
    strcpy(e.name,notify->getUser().name.c_str());
    e.dest_pid=user.pid;
    msgsnd(fd,&e,size_event(e)-sizeof(long),0);
}

void sendMessage(string message,User &user)
{
    int fd=retrieve_msqid();
    MsgEvent e;
    strcpy(e.dest_ip,user.ip.c_str());
    strcpy(e.src_ip,notify->getUser().ip.c_str());
    strcpy(e.content,message.c_str());
    strcpy(e.name,notify->getUser().name.c_str());
    e.dest_pid=user.pid;
    msgsnd(fd,&e,size_event(e)-sizeof(long),0);
}

void setUser(User &user)
{
    cout<<user.ip<<endl;
    notify->setUser(user);
}

void setStatus(Status status)
{
    notify->user->status=status;
}

User getUserByIpAndPid(string ip,int pid)
{
    vector<User> users=getOnlineUsers();
    int size=users.size();
    while(--size>=0)
    {
        if(users[size].ip == ip && users[size].pid == pid)
        {
            return users[size];
        }
    }
}

int search_user_index(string ip, int pid)
{
	return discover->search_user_index(ip,pid);
}

User search_user(int id)
{
	return discover->search_user(id);
}
